import io
import math

import cv2
import numpy as np
import random

import pytesseract
import requests
from PIL import Image

img_path = fr'C:\Users\Administrator\Desktop\verify_{random.random()}.png'


def handle_image_by_bytes(img_bytes, banBlack=True, lang=None, config=''):
    """
    传入本地图片路径，返回验证码
    :param file_path:
    :return:
    :author: 褚天舒
    :modify by bob at 2018-05-31
    """
    if type(img_bytes) == bytes:
        # base64 转 bytes 一维数组
        img_bytes = np.fromstring(img_bytes, np.uint8)
        # bytes 转 bytes 二维数组
        img_bytes = cv2.imdecode(img_bytes, cv2.COLOR_GRAY2RGB)
        # 颜色滤波
        img_bytes = cv2.bilateralFilter(img_bytes, 9, 75, 75)
        # 彩色图 转 灰图
        img_bytes = cv2.cvtColor(img_bytes, cv2.COLOR_BGR2GRAY)
        # 灰图 转 灰度化后的彩色图
        img_bytes = cv2.cvtColor(img_bytes, cv2.COLOR_GRAY2RGB)
        # 判断是否转化黑色像素点,即二值化（阈值10）
        if banBlack:
            x = 0
            for temp_x in img_bytes:
                y = 0
                for temp_y in temp_x:
                    if temp_y[0] == temp_y[1] and temp_y[1] == temp_y[2] and temp_y[0] < 10:
                        img_bytes[x][y] = [255, 255, 255]
                    y = y + 1
                x = x + 1
    # 识别图像文字并返回
    return pytesseract.image_to_string(img_bytes, lang=lang, config=config)


def down_load_single_img(path, value=140):
    image_url = f'http://www.gkyc.cn:88/vcodeimg.jsp?{random.random()}'
    resp = requests.get(image_url)
    img = Image.open(io.BytesIO(resp.content))
    # img.show()
    img = img.convert("L")
    WHITE, BLACK = 255, 0
    img = img.point(lambda x: WHITE if x > 100 else BLACK)
    img = img.convert('1')
    # img.show()
    file_name = fr'{path}\verify_{100}\verify_{value}_{math.floor(random.random()*1000)}.png'
    img.save(file_name, "PNG")
    img.close()

    # s = handle_image_by_bytes(resp.content)
    # print(s)


dir = r'C:\Users\Administrator\Desktop\verify_1'
# for i in range(255, 50, -5):
#     down_load_single_img(dir, value=i)

down_load_single_img(dir, value=55)
